#!/bin/zsh

# Try to attach to Tmux, or start a new Tmux. It won't be necessary to
# do anything else here, as the rest of this file will only run in the
# shells started within Tmux (or if Tmux isn't installed).
function t {
  if hash tmux 2>/dev/null; then
    if [[ -z "$TMUX" ]] && [[ -z "$SSH_CLIENT" ]] && [[ -z "$SSH_TTY" ]]; then

      tmux ls | grep "^default:" >/dev/null 2>&1
      if [[ "$?" == 1 ]]; then
        tmux new-session -s default
      else
        tmux attach-session -t default
      fi
    fi
  fi
}

# In case you want to see a new MOTD, you can just call this function.
function motd () {
  # Set up some ANSI colors real quick.
  WHITE="\e[38;5;255m"
  GRAY="\e[38;5;239m"
  SILVER="\e[38;5;245m"

  # Output a fortune on login if the program exists.
  # This generates a very elaborate box. Perl is used to pad each line of fortune
  # with spaces so that the right edge of the box aligns. This proved to be
  # difficult if not impossible to do with awk/sed. I obviously hold my ASCII
  # boxes in very high regard.
  #
  # This should really be replaced with a small ruby or python script.
  which fortune > /dev/null 2>&1 && which sed > /dev/null 2>&1
  if (( $? == 0 )); then
    HEAD="╡ ${WHITE}M${SILVER}essage ${WHITE}O${SILVER}f ${WHITE}T${SILVER}he ${WHITE}D${SILVER}ay${GRAY} ╞"
    TOP_LEN=$(( $COLUMNS - 32 ))
    BOTTOM_LEN=$(( $COLUMNS - 10 ))
    TOP_LINE=${(l:$TOP_LEN::═:)}
    BOTTOM_LINE=${(l:$BOTTOM_LEN::═:)}

    echo "$WHITE╒═$SILVER════$GRAY$TOP_LINE$HEAD$SILVER═$WHITE═╕"
    fortune -s | perl -e 'my $cols=shift @ARGV; while (<>) { chomp; s/\t/    /g; print "│ ".$_.(" " x ($cols-length()-4))."│\n"; }' ${COLUMNS}
    echo "$WHITE╘═$SILVER═$GRAY$BOTTOM_LINE$SILVER════$WHITE═╛"
  fi
}

function stock {
  if [ -z "$1" ]; then
    echo "Display current stock prices from Yahoo! Finance."
    echo
    echo "Usage: $0 SYMBOL [SYMBOL ...]"
    echo
    echo "  SYMBOL  A valid stock ticker symbol. You may supply several"
    echo "          symbols separated by spaces."
    return 1
  fi

  stocks="${(j:+:)@}"
  values="$(curl -s "http://download.finance.yahoo.com/d/quotes.csv?s=${stocks}&f=nl1c1")"

  printf '\e[1;4m%+30s %+7s %+7s\e[0m\n' 'Name' 'Price' 'Change'
  for line in "${(f)values}"; do
    columns=("${(@s:,:)line}")
    name="${columns[1]:1:-1}"
    price="${columns[2]}"
    change="${columns[3]}"

    if [[ "${change[1]}" == "-" ]]; then
      color='\e[31m'
    else
      color='\e[32m'
    fi

    printf '%+30s $%-7.2f %b$%-7.2f%b\n' "${name}" "${price}" "${color}" "${change}" '\e[0m'
  done
}

function print_colors {
  for color in {000..255}; do
    print -P -- "%F{$color}Color $color XXXXXXXXX"
  done
}
